import React, { Component } from 'react'
import { Card, Button, Table, Modal, message,Form, Input, Select  } from 'antd'
import {reqGetUserlist, reqDeleteUser, reqAddOrUpdateUser} from '../../api/api'
import dayjs from 'dayjs'

export default class User extends Component {

  state = {
    users: [],
    roles: [],
    showModal: 0,
    isUpdateModal: 0
  }

  myForm = React.createRef()

  initColumns = () => {
    this.columns = [
      {
        title: '用户名',
        dataIndex: 'username'
      },
      {
        title: '邮箱',
        dataIndex: 'email'
      },
      {
        title: '电话',
        dataIndex: 'phone'
      },
      {
        title: '注册时间',
        dataIndex: 'create_time',
        render: (user) => {
          return dayjs(user.create_time).format ('DD/MM/YYYY')
        }
      },
      {
        title: '所属角色',
        dataIndex: 'role_id',
        // 返回来的后台数据有些没有role_id 手动指定一个测试'5e171d55d59eb648d4ed66a8'
        render: (role_id='5e171d55d59eb648d4ed66a8') => this.state.roles.find (role => role._id === role_id).name || ''
      },
      {
        title: '操作',
        render: (user) => (
          <span>
            <Button type='primary' onClick={() => {this.updateUserModal(user)}}>修改</Button> &nbsp;
            <Button type='primary' onClick={() => {this.deleteUser (user)}}>删除</Button>
          </span>
        )
      }
    ]
  }

  // 所有用户列表
  getUserList = async () => {
    const result = await reqGetUserlist ()
    if (result.status === 0) {
      const {users, roles} = result.data
      this.setState ({users, roles})
    }
  }

  // 删除用户
  deleteUser = (user) => {
    Modal.confirm({
      title: `确认删除${user.username}吗?`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        const result = (await reqDeleteUser(user._id))
        if (result.status === 0) {
          message.success('删除用户成功')
          // 重新获取用户列表
          this.getUserList()
        }
      }
    });
  }


  addUserModal = () => {
    this.user = null
    this.setState ({showModal: 1})
  }

  updateUserModal = (user) => {
    this.user = user // 保存User到this中
    this.setState ({showModal: 1, isUpdateModal: 1}, () => {
      // 解决异步问题，动态更新modal显示问题
      this.myForm.current.setFieldsValue ({
        username: user.username,
        email: user.email,
        phone: user.phone,
        role_id: user.role_id
      })
    }
    )
  }

  // 添加或更新用户
  handleAddOk = async () => {
    if (this.state.isUpdateModal === 1) {
      // 更新
      const { _id } = this.user
      const { username, phone, email, role_id } = this.myForm.current.getFieldsValue()
      const newUser = { _id, username, phone, email, role_id }
      const result = await reqAddOrUpdateUser (newUser)
      // console.log (result)
      if (result.status === 0) {
        message.success(`修改用户成功`)
        // 更新用户列表
        this.getUserList ()
        this.setState ({showModal: 0, isUpdateModal:0})
      }
    } else {
      // 添加
      const newUser = this.myForm.current.getFieldsValue()
      const result = await reqAddOrUpdateUser (newUser)
      // console.log (result)
      if (result.status === 0) {
        message.success(`添加用户成功`)
        // 更新用户列表
        this.getUserList ()
        this.setState ({showModal: 0})
      }
    }
  }

  handleCancel = () => {
    // 清除数据
    this.myForm.current.resetFields ()

    this.setState({ showModal: 0, isUpdateModal: 0})
  }

  UNSAFE_componentWillMount () {
    this.initColumns ()
  }

  componentDidMount () {
    this.getUserList ()
  }

  render() {

    const {users, showModal, roles,isUpdateModal} = this.state 

    const title = (
      <span>
        <Button type='primary' onClick={this.addUserModal}>添加用户</Button> &nbsp;
      </span>
    )
    return (
      <Card title={title}>
        <Table
        bordered
        sticky
        dataSource={users}
        columns={this.columns}
        rowKey='_id'
        pagination={{ defaultPageSize: 5, showQuickJumper: true }}
        onRow={this.onRow}>
        </Table>

        <Modal 
          title={isUpdateModal===1? '修改用户':'添加用户'} 
          visible={showModal === 1} 
          onOk={this.handleAddOk} 
          onCancel={this.handleCancel}>
        <Form
          ref={this.myForm}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 15 }}
          // initialValues={{
          //   username: user.username,
          //   email: user.email,
          //   phone: user.phone,
          //   role_id: user.role_id
          // }} 不能动态更新
        >
          <Form.Item label='用户名' name='username' rules={[
            {
              required: true,
              message: '请输入用户名',
            }
          ]}>
            <Input placeholder='请输入用户名' />
          </Form.Item>
          {
            isUpdateModal===1? null:
            <Form.Item label='密码' name='password' rules={[
              {
                required: true,
                message: '请输入密码',
              }
            ]}>
              <Input placeholder='请输入密码' />
            </Form.Item>
          }
          <Form.Item label='手机号' name='phone' rules={[
            {
              required: true,
              message: '请输入手机号',
            }
          ]}>
            <Input placeholder='请输入手机号' />
          </Form.Item>
          <Form.Item label='邮箱' name='email' rules={[
            {
              required: true,
              message: '请输入邮箱',
            }
          ]}>
            <Input placeholder='请输入邮箱' />
          </Form.Item>
          <Form.Item label='角色' name='role_id' rules={[
            {
              required: true,
              message: '请选择所属角色',
            }
          ]}>
            <Select>
              {roles.map((role) => {
                return (
                  <Select.Option value={role._id} key={role._id}>{role.name}</Select.Option>
                )
              })}
            </Select>
          </Form.Item>
        </Form>
        </Modal>

      </Card>
    )
  }
}
